import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 权限判断指令
import permission from '@/directive/permission/index.js'
import checkPermission from '@/utils/permission' // 权限判断函数
import { fileTemplateList } from '@/api/company_self_ass'
import { getFileType, isImage, isMsOfficeFile, isPdf } from '@/utils/index'
import axios from 'axios'

// 默认查询条件
const defaultListQuery = {
  page: 1,
  limit: 10,
  ordering: 'id'
}

export default {
  components: { Pagination },
  directives: { permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'primary',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    },
    textFilter(status) {
      const statusMap = {
        0: '待审核',
        1: '通过',
        2: '不通过'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      // 查询条件
      listQuery: Object.assign({}, defaultListQuery)
    }
  },
  created() {
    this.getList()
  },
  watch: {
  },
  methods: {
    checkPermission,

    downloadFile(row) {
      // window.open(row.url)
      const url = row.url
      const filename = row.name
      const fileType = getFileType(url)
      if (isPdf(fileType)) {
        axios({
          url: url,
          method: 'get'
        }).then(res => {
          const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }))

          const link = document.createElement('a')

          link.style.display = 'none'

          link.href = url

          link.setAttribute('download', filename)

          document.body.appendChild(link)

          link.click()

          document.body.removeChild(link)
        })
      } else {
        window.open(url)
      }
    },

    onlineRead(row) {
      // console.log(row.url)
      // window.open('https://view.officeapps.live.com/op/view.aspx?src=' + row.url)
      const url = row.url
      const fileType = getFileType(url)
      if (isMsOfficeFile(fileType)) {
        window.open('https://view.officeapps.live.com/op/view.aspx?src=' + url)
      } else if (isImage(fileType)) {
        this.imgUrl = url
        console.log(this.imgUrl)
        this.previewImg = true
      } else {
        window.open(url)
      }
    },

    // 获取表格数据
    getList() {
      this.listLoading = true
      fileTemplateList(this.listQuery).then(res => {
        this.list = res.results
        this.total = res.count
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },

    // 搜索事件
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    }

  }
}
